﻿using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Shop.DB;
using Shop.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shop.Application.Cart
{
    public class GetCart
    {
        private ISession _session;
        private DBContext _context;

        public GetCart(ISession session, DBContext context)
        {
            _session = session;
            _context = context;
        }

        public IEnumerable<CartInput> Do()
        {
            //获取session
            var str = _session.GetString("Cart");
            if (string.IsNullOrEmpty(str))
                return new List<CartInput>();

            var carts = JsonConvert.DeserializeObject<List<CartProduct>>(str);
            var response = _context.Stocks
                .AsEnumerable()
                .Where(x => carts.Any(y => y.StockID == x.StockID))
                .Select(x => new CartInput
                {
                    StockID = x.StockID,
                    Name = _context.Products.FirstOrDefault(y => y.ProductID == x.ProductID).Name,
                    Count = carts.FirstOrDefault(y => y.StockID == x.StockID).Count,
                    Value = $"¥{_context.Products.FirstOrDefault(y => y.ProductID == x.ProductID).Value.ToString("N2")}"
                }).ToList();
            return response;
        }
    }
}
